package org.example.shop_front_api.controller;

import org.example.shop_front_api.entity.ApiAccount;
import org.example.shop_front_api.service.ApiAcccountService;
import org.example.shop_front_api.utils.JsonResult;
import org.example.shop_front_api.utils.JwtUtils;
import org.example.shop_front_api.utils.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("api/api_account")
public class ApiAccountController {
    @Autowired
    private JwtUtils jwtUtils; // 已注入JwtUtils实例
    @Autowired
    private ApiAcccountService apiAcccountService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Value("${salt}")
    private String salt;

    @PostMapping("register")
    public JsonResult register(@RequestBody ApiAccount account) {
        // 注册逻辑不变...
        String username = account.getUsername();
        String password = account.getPassword();
        if (username == null || password == null) {
            return JsonResult.failed("账号或密码不能为空");
        }
        ApiAccount accountInfo = apiAcccountService.getAccountByUsername(username);
        if (accountInfo != null) {
            return JsonResult.failed("该账号已经存在，请重新输入.");
        }
        account.setPassword(Md5Utils.encrypt(password));
        int result = apiAcccountService.insertAccount(account);
        return result > 0 ? JsonResult.success("注册成功", null) : JsonResult.failed("注册失败.");
    }

    @GetMapping("set")
    public JsonResult set(@RequestParam("id") int id, @RequestParam("enabled") int enabled) {
        // 激活逻辑不变...
        int result = apiAcccountService.updateApiAccountEnabled(id, enabled);
        return result > 0 ? JsonResult.success("操作成功", null) : JsonResult.failed("操作失败.");
    }

    @PostMapping("login")
    public JsonResult login(@RequestBody ApiAccount account) {
        // 登录参数验证逻辑不变...
        String username = account.getUsername();
        String password = account.getPassword();
        if (username == null || password == null) {
            return JsonResult.failed("账号或密码不能为空");
        }
        String safePassword = Md5Utils.encrypt(password);
        ApiAccount accountInfo = apiAcccountService.getAccountByUsername(username);
        if (accountInfo == null || !accountInfo.getPassword().equals(safePassword)) {
            return JsonResult.failed("账号或密码输入错误.");
        }
        if (accountInfo.getEnabled() == 0) {
            return JsonResult.failed("该账号不可用，请联系管理员.");
        }

        // 关键修复：用注入的实例调用非静态方法（去掉类名JwtUtils，改用实例jwtUtils）
        String jwtToken = jwtUtils.generateToken(username); // 修复静态调用问题

        // 存储Redis时，建议使用JwtUtils中定义的过期时间（保持一致）
        stringRedisTemplate.opsForValue().set(
                jwtToken,
                jwtToken,
                jwtUtils.getExpiration(), // 从实例获取过期时间（与JWT一致）
                TimeUnit.MILLISECONDS
        );

        return JsonResult.success("登录成功", jwtToken);
    }
}